package com.windmill.cmd;

import iqq.im.QQException;
import iqq.im.bean.QQGroupMember;
import iqq.im.bean.QQMsg;
import iqq.im.bean.QQUser;
import iqq.im.bean.content.FontItem;
import iqq.im.bean.content.TextItem;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.windmill.bean.GroupUser;
import com.windmill.core.MargicCardClient;

public class RobotReplyDispatcher implements Runnable{
	private static final Logger LOG = LoggerFactory.getLogger(RobotReplyDispatcher.class);
	private BlockingQueue<QQMsg> msgQueue;
	private MargicCardClient client;
	private CommandDispatcher command;
	private Thread dispatchThread;
	private ActionListener listener;
	public RobotReplyDispatcher(MargicCardClient client, ActionListener actionListener){
		this.client = client;
		this.listener = actionListener;
		init();
	}	
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 * 处理被动事件，如：
	 * 记录发主记录次数，欢迎新人
	 */
	public void run() {
		while(true){
			try {
				QQMsg msg = msgQueue.take();
				msg = parseMsg(msg);//得到msg中发送者QQ和名称
				autoReplyMsg(msg);
			} catch (Exception e) {
				e.printStackTrace();
				LOG.error("RobotReply error");
			}
		}
	}
	/**
	 * 包装显示消息
	 * @throws QQException 
	 */
	public QQMsg parseMsg(QQMsg msg) throws QQException{		
		StringBuffer displayUI = new StringBuffer();
		if(msg.getType()==QQMsg.Type.GROUP_MSG){
			QQGroupMember member = client.getGroupMember(msg);
			if(member.isNewMember()) {
				member.setNewMember(false);
				welcomeNewMember(msg);//欢迎新人
			}
			recordChat(msg);//发言统计
			displayUI.append(" [群消息] ");			
		}else if(msg.getType()==QQMsg.Type.SESSION_MSG){
			displayUI.append(" [临时会话] ");			
		}else if(msg.getType()==QQMsg.Type.BUDDY_MSG){
			displayUI.append("　[好友消息] ");	
			client.getQQ(msg);
		}
		QQUser user = msg.getFrom();
		displayUI.insert(0,user.getNickname()+"("+user.getQQ()+"):"+msg.getText());
		displayUI.append(" "+format(msg.getDate()));
		if(listener!=null)//回显消息到UI界面
			listener.actionPerformed(new ActionEvent(msg.getFontColor(), 0, displayUI.toString()));
		return msg;
	}
	/**
	 * @param msg
	 * @throws QQException
	 */
	public void autoReplyMsg(QQMsg msg) throws QQException {
		Command cmd = new Command();
		cmd.setUser(msg.getFrom());
		Pattern	pattern = Pattern.compile("[#＃]([a-zA-Z?？]{1,4}) *([^ ]*) ?([^ ]*) ?([^ ]*)");
		Matcher	matcher = pattern.matcher(msg.getText());
		if(matcher.find()){
			cmd.setCmd(matcher.group(1));	
			cmd.setMsgType(msg.getType());
			if(matcher.group(2)==null||"".equals(matcher.group(2))){
				cmd.setParam1(cmd.getUser().getQQ()+"");
			}else{
				cmd.setParam1(matcher.group(2));
				cmd.setParam2(matcher.group(3));
				cmd.setParam3(matcher.group(4));
			}
			if(cmd.getUser().getQQ()!=0){ 
				String result = command.execute(cmd);
				if(result!=null&&!"".equals(result)){
					msg.setType(cmd.getMsgType());
					sendMsg(result, msg);									
				}
			}
		}
	}
	
	
	/**
	 * 回复消息
	 */
	private void sendMsg(String replyMsg, QQMsg msg) {
		QQMsg sendMsg = new QQMsg();
		sendMsg.setType(msg.getType()); 
		sendMsg.setTo(msg.getFrom());
		 if(replyMsg.length()>300||msg.getType()==QQMsg.Type.SESSION_MSG){
				sendMsg.setType(QQMsg.Type.SESSION_MSG);
		}else if(msg.getType()==QQMsg.Type.GROUP_MSG){
			if(msg.getFrom() instanceof QQGroupMember)
				sendMsg.setGroup(((QQGroupMember)msg.getFrom()).getGroup());                   		
		}
		sendMsg.addContentItem(new TextItem(replyMsg));     
		sendMsg.addContentItem(new FontItem());	
		if(listener!=null)
			listener.actionPerformed(new ActionEvent(Color.RED, 0, replyMsg));
		client.sendMsg(sendMsg, null); 
	}

	
	/** 记录发言
	 * @param from
	 */
//	private Random random = new Random();
	private void recordChat(QQMsg msg) {
		QQUser u = msg.getFrom();
		GroupUser guser = client.getDataStore().getGoupUserByQQ(u.getQQ());
		if(guser==null){
			guser = new GroupUser();
			guser.setQq(u.getQQ());
			guser.setGroupId(msg.getGroup().getGid());
			client.getDataStore().addGroupUser(guser);
		}
		if(System.currentTimeMillis()-guser.getChat().getLastDate().getTime()>86400000){
			Calendar cal = new GregorianCalendar();
			cal.setTime(new Date());
			StringBuffer sendMsg = new StringBuffer(guser.getCardName()+":");
			int hour = cal.get(Calendar.HOUR_OF_DAY);
			if(hour>=0&&hour<6){
				sendMsg.append("凌晨好！");
			}else if(hour>=6&&hour<8){
				sendMsg.append("早上好！");
			}else if(hour>=9&&hour<12){
				sendMsg.append("上午好！");
			}else if(hour>=12&&hour<2){
				sendMsg.append("中午好！");
			}else if(hour>=2&&hour<19){
				sendMsg.append("下午好！");
			}else if(hour>=20){
				sendMsg.append("晚上好！");
			}
			sendMsg.append(client.getDataStore().getWelcome().replace("@self", guser.getCardName()));
			sendMsg(sendMsg.toString(), msg);
		}
		guser.setCardName(u.getNickname());
		guser.getChat().chat();
	}
	
	/**
	 * 欢迎新人
	 * @throws QQException 
	 */
	private void welcomeNewMember(QQMsg msg) throws QQException {
//		QQActionEvent event = client.getUserMainCardInfo(msg.getFrom().getQQ()+"", null).waitFinalEvent();
//		UserMainCardInfo main = (UserMainCardInfo) event.getTarget();
		sendMsg(msg.getFrom().getNickname()+":您好，"+msg.getGroup().getName()+"欢迎您的加入，祝你玩的愉快！",msg);
	}
	/**
	 * 时间格式
	 * */
	private DateFormat fmt = new SimpleDateFormat("HH:mm:ss");
	public String format (Date date){
		return fmt.format(date);
	}
	/**
	 * pushMsg进等待队列
	 */
	public void pushMsg(QQMsg msg) {
		this.msgQueue.add(msg);		
	}
	/**
	 * init
	 */
	private void init() {
		this.command = new CommandDispatcher(client);
		this.msgQueue = new LinkedBlockingQueue<QQMsg>();
		this.dispatchThread = new Thread(this);
		this.dispatchThread.start();
	}
	
}
